<template>
  <div class="layui-container">
    <fly-panel></fly-panel>
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md8 content detail">
        <div class="fly-panel detail-box">
          <h1>{{page.title}}</h1>
          <div class="fly-detail-info">
            <!-- <span class="layui-badge">审核中</span> -->
            <span
              class="layui-badge layui-bg-green fly-detail-column"
              v-if="page.catalog === 'logs'"
            >动态</span>
            <span
              class="layui-badge layui-bg-green fly-detail-column"
              v-else-if="page.catalog === 'share'"
            >分享</span>
            <span
              class="layui-badge layui-bg-green fly-detail-column"
              v-else-if="page.catalog === 'ask'"
            >提问</span>
            <span
              class="layui-badge layui-bg-green fly-detail-column"
              v-else-if="page.catalog === 'advise'"
            >建议</span>
            <span
              class="layui-badge layui-bg-green fly-detail-column"
              v-else-if="page.catalog === 'discuss'"
            >交流</span>
            <span
              class="layui-badge layui-bg-green fly-detail-column"
              v-else-if="page.catalog === 'notice'"
            >公告</span>

            <span class="layui-badge" style="background-color: #999;" v-if="page.isEnd === '0'">未结</span>
            <span class="layui-badge" style="background-color: #5FB878;" v-else>已结</span>

            <span class="layui-badge layui-bg-black" v-show="page.isTop === '1'">置顶</span>
            <span
              class="layui-badge layui-bg-red"
              v-for="(tag,index) in page.tags"
              :key="'tags'+index"
              :class="tag.class"
            >{{tag.name}}</span>
            <!--
            <div class="fly-admin-box" data-id="123">
              <span class="layui-btn layui-btn-xs jie-admin" type="del">删除</span>

              <span class="layui-btn layui-btn-xs jie-admin" type="set" field="stick" rank="1">置顶</span>
              <span class="layui-btn layui-btn-xs jie-admin" type="set" field="stick" rank="0" style="background-color:#ccc;">取消置顶</span>

              <span class="layui-btn layui-btn-xs jie-admin" type="set" field="status" rank="1">加精</span>
              <span class="layui-btn layui-btn-xs jie-admin" type="set" field="status" rank="0" style="background-color:#ccc;">取消加精</span>
            </div>--->
            <span class="fly-list-nums">
              <a href="#comment">
                <i class="iconfont" title="回答">&#xe60c;</i>
                {{page.answer}}
              </a>
              <i class="iconfont" title="人气">&#xe60b;</i>
              {{page.reads}}
            </span>
          </div>
          <div class="detail-about">
            <a class="fly-avatar" href="javascript:;">
              <img :src="page.uid ? page.uid.pic : '/img/bear-200-200.jpg'" />
            </a>
            <div class="fly-detail-user">
              <a href="../user/home.html" class="fly-link">
                <cite class="mr1">{{page.uid ? page.uid.nickname :'imooc'}}</cite>
                <!-- <i class="iconfont icon-renzheng" title="认证信息："></i> -->
                <i
                  class="layui-badge fly-badge-vip"
                  v-if="page.uid ? page.uid.isVip : false"
                >VIP {{page.uid.isVip}}</i>
              </a>
              <span>{{page.created|moment}}</span>
            </div>
            <div class="detail-hits" id="LAY_jieAdmin" data-id="123">
              <span style="padding-right: 10px; color: #FF7200">悬赏：{{page.fav}}</span>
              <div class="layui-btn-container fly-detail-admin pt1">
                <router-link class="layui-btn layui-btn-sm jie-admin" :to="{name: 'edit'}">编辑</router-link>
                <a
                  class="layui-btn layui-btn-sm jie-admin-collect"
                  :class="{'layui-btn-primary': page.isFav}"
                  @click.prevent="setCollect()"
                >{{page.isFav ? '取消收藏': '收藏'}}</a>
              </div>
            </div>
          </div>
          <div class="detail-body photos" v-html="content"></div>
        </div>
        <div class="fly-panel detail-box" id="flyReply">
          <fieldset class="layui-elem-field layui-field-title" style="text-align: center;">
            <legend>回帖</legend>
          </fieldset>
          <ul class="jieda" id="jieda">
            <li
              data-id="111"
              class="jieda-daan"
              v-for="(item,index) in comments"
              :key="'comment'+index"
            >
              <div class="detail-about detail-about-reply">
                <a class="fly-avatar" href>
                  <img :src="item.cuid ? item.cuid.pic :'/img/bear-200-200.jpg'" alt=" " />
                </a>
                <div class="fly-detail-user">
                  <a href class="fly-link">
                    <cite class="mr1">{{item.cuid ? item.cuid.nickname : 'imooc'}}</cite>
                    <!-- <i class="iconfont icon-renzheng" title="认证信息：XXX"></i> -->
                    <i
                      class="layui-badge fly-badge-vip"
                      v-if="item.cuid && item.cuid.isVip !== '0' ? item.cuid.isVip : false"
                    >VIP{{item.cuid.isVip}}</i>
                  </a>

                  <span v-if="index === 0">(楼主)</span>
                  <!--
                <span style="color:#5FB878">(管理员)</span>
                <span style="color:#FF9E3F">（社区之光）</span>
                <span style="color:#999">（该号已被封）</span>
                  -->
                </div>

                <div class="detail-hits">
                  <span>{{item.created | moment}}</span>
                </div>

                <!-- <i class="iconfont icon-caina" title="最佳答案"></i> -->
              </div>
              <div class="detail-body jieda-body photos" v-richtext="item.content"></div>
              <div class="jieda-reply">
                <span class="jieda-zan" :class="item.handed === 1 ? 'zanok':''" type="zan">
                  <i class="iconfont icon-zan"></i>
                  <em>{{item.hands}}</em>
                </span>
                <span type="reply">
                  <i class="iconfont icon-svgmoban53"></i>
                  回复
                </span>
                <div class="jieda-admin">
                  <span
                    @click="editComment(item)"
                    v-show="page.isEnd === '0' && item.cuid._id === user._id"
                  >编辑</span>
                  <!-- <span type="del">删除</span> -->
                  <span
                    class="jieda-accept"
                    v-show="page.isEnd === '0' && item.cuid._id === user._id"
                    @click="setBest(item)"
                  >采纳</span>
                </div>
              </div>
            </li>

            <!-- 无数据时 -->
            <li class="fly-none" v-if="comments.length === 0">消灭零回复</li>
          </ul>
          <!--分页-->
          <fly-page
            v-show="total > 0"
            :total="total"
            :size="size"
            :showType="'icon'"
            :showEnd="true"
            :hasSelect="true"
            :hasTotal="true"
            :current="current"
            @changeCurrent="handleCurrent"
            @changeLimit="handleLimit"
          ></fly-page>
          <validation-observer ref="observer" v-slot="{validate}">
            <div class="layui-form layui-form-pane">
              <form>
                <fly-editor @changeContent="addContent" :initContent="editInfo.content"></fly-editor>
                <div class="layui-form-item">
                  <validation-provider
                    ref="code"
                    vid="code"
                    name="code"
                    rules="required|length:4"
                    v-slot="{errors}"
                  >
                    <div class="layui-row">
                      <label for="L_vercode" class="layui-form-label">验证码</label>
                      <div class="layui-input-inline">
                        <input
                          type="text"
                          name="code"
                          placeholder="请输入验证码"
                          v-model="code"
                          autocomplete="off"
                          class="layui-input"
                        />
                      </div>
                      <div class>
                        <span style="color: #c00;" class="svg" v-html="svg" @click="_getCode()"></span>
                      </div>
                    </div>
                    <div class="error layui-form-mid">
                      <span style="color: red;">{{errors[0]}}</span>
                    </div>
                  </validation-provider>
                </div>
                <div class="layui-form-item">
                  <button class="layui-btn" type="button" @click="validate().then(submit)">提交回复</button>
                </div>
              </form>
            </div>
          </validation-observer>
        </div>
      </div>
      <div class="layui-col-md4">
        <fly-hotlist></fly-hotlist>
        <fly-ads></fly-ads>
        <fly-links></fly-links>
      </div>
    </div>
  </div>
</template>

<script>
import Ads from '@/components/siderbar/Ads'
import Hotlist from '@/components/siderbar/Hotlist'
import Links from '@/components/siderbar/Links'
import Panel from '@/components/Panel'
import CodeMix from '@/mixin/code'
import Editor from '@/components/modules/editor/Index'
import Pagination from '@/components/modules/page/Index'
import { getDetail } from '@/api/content'
import { getComments, addComment } from '@/api/comments'
import { escapeHtml } from '@/utils/escapeHtml'
export default {
  name: 'Detail',
  mixins: [CodeMix],
  props: ['tid'],
  components: {
    'fly-panel': Panel,
    'fly-hotlist': Hotlist,
    'fly-ads': Ads,
    'fly-links': Links,
    'fly-editor': Editor,
    'fly-page': Pagination
  },
  data () {
    return {
      current: 0,
      size: 10,
      total: 0,
      page: {
        isFav: false,
        isEnd: 0,
        content: ''
      },
      comments: [],
      editInfo: {
        content: '',
        code: '',
        sid: ''
      }
    }
  },
  mounted () {
    // window.vue = scrollToElem
    this.getPostDetail()
    this.getCommentsList()
  },
  watch: {
    tid (newval, oldval) {
      this.getPostDetail()
      this.getCommentsList()
    }
  },
  methods: {
    addContent (val) {
      this.editInfo.content = val
    },
    async submit () {
      const isValid = await this.$refs.observer.validate()
      if (!isValid) {
        return
      }
      // 用户未登录
      const isLogin = this.$store.state.isLogin
      if (!isLogin) {
        this.$pop('shake', '请先登录')
        return
      }

      // 判断用户是否修改了内容
      if (this.editInfo.content === '') {
        this.$pop('shake', '评论内容不能为空')
        return
      }

      this.editInfo.code = this.code
      this.editInfo.sid = this.$store.state.sid
      this.editInfo.tid = this.tid

      addComment(this.editInfo).then((res) => {
        if (res.code === 200) {
          this.$alert('发表评论成功')
          this.editInfo.content = ''
          this.code = ''
          const user = this.$store.state.userInfo
          const cuid = {
            _id: user._id,
            nickname: user.nickname,
            isVip: user.isVip,
            pic: user.pic
          }
          res.data.cuid = cuid
          this.comments.push(res.data)

          requestAnimationFrame(() => {
            this.$refs.observer.reset()
          })
          this._getCode()
        } else {
          this.$alert(res.msg)
        }
      })
    },
    // 更改当前页码
    handleCurrent (val) {
      this.current = val
      this.getCommentsList()
    },
    handleLimit (val) {
      this.size = val
      this.getCommentsList()
    },
    getPostDetail () {
      getDetail(this.tid).then((res) => {
        if (res.code === 200) {
          this.page = res.data
        } else {
          this.$alert(res.msg)
        }
      })
    },
    getCommentsList () {
      getComments({
        tid: this.tid,
        page: this.current,
        limit: this.size
      }).then((res) => {
        if (res.code === 200) {
          this.comments = res.data
          this.total = res.total
        } else {
          this.$alert(res.msg)
        }
      })
    },
    // 编辑回复内容
    editComment (item) {
      this.editInfo.content = item
    },
    setBest (item, index) {
      console.log('🚀 ~ file: Detail.vue ~ line 355 ~ setBeset ~ item', item)
    }
  },
  computed: {
    // 根据填写的content 内容转化成对应的replaceHtml
    content () {
      if (typeof this.page.content === 'undefined' || this.page.content.trim() === '') {
        return
      }
      return escapeHtml(this.page.content)
    },
    user () {
      return this.$store.state.userInfo
    }
  }
}
</script>

<style lang="scss" scoped>
.fly-detail-admin {
  text-align: right;
  border-top: 1px dotted #eaeaea;
  background: #f8f8f8;
}
.fly-detail-info {
  span {
    margin-right: 5px;
  }
}
</style>
